#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# 日志函数
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[警告] $1${NC}"
}

error() {
    echo -e "${RED}[错误] $1${NC}" >&2
}

info() {
    echo -e "${BLUE}[信息] $1${NC}"
}

# 错误处理
die() {
    error "$1"
    read -p "按回车键退出..."
    exit 1
}

# 检查Docker服务状态（适配群辉DSM）
check_docker_service() {
    if ! docker version >/dev/null 2>&1; then
        error "Docker服务未运行或无法连接"
        
        # 在群辉DSM上，Docker通常通过套件中心管理
        if [ -f /etc/synoinfo.conf ]; then
            error "请在群辉DSM的套件中心中启动Docker服务"
            die "或者通过DSM网页界面启动Docker"
        else
            # 其他系统尝试启动
            if command -v systemctl >/dev/null 2>&1; then
                systemctl start docker || die "启动Docker服务失败"
            elif command -v service >/dev/null 2>&1; then
                service docker start || die "启动Docker服务失败"
            else
                die "无法启动Docker服务，请手动启动"
            fi
            sleep 3
        fi
    fi
    log "Docker服务运行正常"
}

# 获取本机IP地址
get_local_ip() {
    local ip
    ip=$(ip -o -4 addr show scope global | awk '{print $4}' | cut -d'/' -f1 | grep -v '127.0.0.1' | head -n1)
    
    if [ -z "$ip" ]; then
        ip=$(hostname -I | awk '{print $1}' | grep -v '^127' | head -n1)
    fi
    
    if [ -z "$ip" ]; then
        ip="localhost"
    fi
    
    echo "$ip"
}

# 精准系统检测
detect_system() {
    # 检测群辉DSM
    if [ -f /etc/synoinfo.conf ] && [ -d /var/packages ]; then
        echo "dsm"
        return
    fi

    # 检测UNRAID
    if [ -f /etc/unraid-version ] && [ -d /boot/config ]; then
        echo "unraid"
        return
    fi

    # 检测FNOS系统
    if grep -q "ID=debian" /etc/os-release 2>/dev/null && ls /vol1* &>/dev/null; then
        echo "fnos"
        return
    fi

    # 检测基于Debian的系统
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        case $ID in
            debian|ubuntu|raspbian)
                echo "debian"
                return
                ;;
            centos|rhel|fedora|almalinux|rocky)
                echo "rhel"
                return
                ;;
        esac
    fi

    echo "linux"
}

# 获取Docker目录
get_docker_dir() {
    local system_type=$1
    local dir=""

    case $system_type in
        "dsm")
            dir=$(find /volume* -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            [ -z "$dir" ] && dir="/volume1/docker"
            ;;
        "fnos")
            dir=$(find /vol*/1000 -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            [ -z "$dir" ] && dir="/vol1/1000/docker"
            ;;
        "unraid")
            dir="/mnt/user/appdata"
            ;;
        *)
            dir="/opt/docker"
            ;;
    esac

    dir=$(echo "$dir" | tr -d '\n\r' | sed 's/\/$//')
    mkdir -p "$dir" || die "无法创建目录 $dir"
    
    echo "$dir"
}

# 检查端口占用
check_port() {
    local port=$1
    if netstat -tuln 2>/dev/null | grep -q ":${port} "; then
        warn "端口 ${port} 已被占用"
        return 1
    fi
    return 0
}

# 获取可用端口
get_available_port() {
    local base_port=$1
    local port=$base_port
    
    while netstat -tuln 2>/dev/null | grep -q ":${port} "; do
        warn "端口 ${port} 已被占用，尝试下一个端口"
        ((port++))
        if [ $port -gt $((base_port + 10)) ]; then
            error "在范围内找不到可用端口"
            return $base_port
        fi
    done
    
    echo $port
}

# 安装Xiaomusic
install_xiaomusic() {
    local base_dir="$1"
    local data_dir="${base_dir}/xiaomusic"
    local conf_dir="${data_dir}/xiaomusic_conf"
    
    # 创建目录
    mkdir -p "$data_dir" "$conf_dir" || die "无法创建Xiaomusic目录"
    
    # 设置目录权限
    chmod 755 "$data_dir" "$conf_dir" 2>/dev/null || warn "无法设置目录权限"

    info "使用Docker目录: ${base_dir}"
    info "Xiaomusic数据目录: ${data_dir}"
    info "Xiaomusic配置目录: ${conf_dir}"

    # 检查端口并获取可用端口
    local original_port=58090
    local actual_port=$(get_available_port $original_port)
    
    if [ "$actual_port" -ne "$original_port" ]; then
        warn "端口 ${original_port} 被占用，使用端口: ${actual_port}"
    else
        info "使用默认端口: ${actual_port}"
    fi

    # 清理旧容器
    if docker ps -aq --filter "name=xiaomusic" >/dev/null 2>&1; then
        info "移除已存在的xiaomusic容器..."
        docker stop xiaomusic >/dev/null 2>&1
        docker rm xiaomusic >/dev/null 2>&1
    fi

    # 运行新容器
    info "正在启动Xiaomusic容器..."
    info "映射端口: ${actual_port}:8090"
    
    if ! docker run -d \
        --name xiaomusic \
        --restart=always \
        -p ${actual_port}:8090 \
        -e XIAOMUSIC_PUBLIC_PORT=${actual_port} \
        -v "${data_dir}:/app/music" \
        -v "${conf_dir}:/app/conf" \
        docker.hanxi.cc/hanxi/xiaomusic; then
        
        error "启动Xiaomusic容器失败，最后20行日志："
        docker logs xiaomusic 2>&1 | tail -n 20
        die "容器启动失败"
    fi

    # 验证容器状态
    info "等待容器启动..."
    for i in {1..15}; do
        if docker ps --filter "name=xiaomusic" --format "{{.Status}}" | grep -q "Up"; then
            break
        fi
        sleep 2
    done

    if ! docker ps --filter "name=xiaomusic" --format "{{.Status}}" | grep -q "Up"; then
        error "容器启动后异常退出，最后20行日志："
        docker logs xiaomusic 2>&1 | tail -n 20
        die "容器运行异常"
    fi

    local ip=$(get_local_ip)
    echo -e "\n${GREEN}========== Xiaomusic 安装成功 ==========${NC}"
    echo -e "访问地址: ${CYAN}http://${ip}:${actual_port}${NC}"
    echo -e "外部端口: ${actual_port}"
    echo -e "内部端口: 8090"
    echo -e "音乐目录: ${data_dir}"
    echo -e "配置目录: ${conf_dir}"
    echo -e "查看日志: ${YELLOW}docker logs -f xiaomusic${NC}"
    echo -e "停止服务: ${YELLOW}docker stop xiaomusic${NC}"
    echo -e "重启服务: ${YELLOW}docker restart xiaomusic${NC}"
    echo -e "容器信息: ${YELLOW}docker inspect xiaomusic${NC}"
    
    if [ "$actual_port" -ne "$original_port" ]; then
        echo -e "\n${YELLOW}注意: 由于原端口被占用，已使用端口 ${actual_port} 替代 ${original_port}${NC}"
    fi
}

# 显示系统信息
show_system_info() {
    info "系统信息:"
    echo -e "  - 系统类型: $(detect_system)"
    echo -e "  - 主机名: $(hostname)"
    echo -e "  - IP地址: $(get_local_ip)"
    echo -e "  - Docker版本: $(docker --version 2>/dev/null | cut -d ',' -f 1 || echo '未知')"
}

# 主流程
main() {
    echo -e "${CYAN}=== Xiaomusic 自动化安装脚本 ===${NC}"
    
    # 检查Docker
    if ! command -v docker &>/dev/null; then
        die "Docker未安装，请在套件中心安装Docker"
    fi
    
    # 检查Docker服务状态（适配群辉）
    check_docker_service
    
    # 显示系统信息
    show_system_info

    # 检测系统并获取目录
    system_type=$(detect_system)
    case $system_type in
        "dsm") 
            log "检测到群辉DSM系统"
            info "建议通过DSM网页界面管理Docker容器"
            ;;
        "fnos") log "检测到FNOS系统" ;;
        "unraid") log "检测到UNRAID系统" ;;
        "debian") log "检测到Debian系系统" ;;
        "rhel") log "检测到RedHat系系统" ;;
        *) log "检测到Linux系统" ;;
    esac

    dir=$(get_docker_dir "$system_type")
    info "使用容器目录: ${dir}"

    # 安装Xiaomusic
    install_xiaomusic "$dir"

    echo
    read -p "按回车键退出..."
}

# 信号处理
trap 'error "脚本被用户中断"; exit 1' INT TERM

# 脚本入口
if [ "$#" -gt 0 ]; then
    case $1 in
        -h|--help)
            echo "用法: $0"
            echo "Xiaomusic 自动化安装脚本"
            echo ""
            echo "环境变量:"
            echo "  默认端口: 58090"
            echo "  数据目录: {docker_dir}/xiaomusic"
            echo "  配置目录: {docker_dir}/xiaomusic/xiaomusic_conf"
            echo ""
            echo "镜像源: docker.hanxi.cc/hanxi/xiaomusic"
            exit 0
            ;;
        *)
            error "未知参数: $1"
            echo "用法: $0 [-h|--help]"
            exit 1
            ;;
    esac
fi

main "$@"